//
// Created by 77873 on 2020/10/12 0012.
//

#ifndef FFMPEGVIDEOPLAYER_AUDIODECODEC_H
#define FFMPEGVIDEOPLAYER_AUDIODECODEC_H

#include "CallBackToJava.h"
#include "DataQueue.h"
#include "PlayStatus.h"

#include <pthread.h>

//opensl es
#include <SLES/OpenSLES.h>
#include <SLES/OpenSLES_Android.h>


extern "C" {
#include <libavutil/time.h>
#include <libavcodec/avcodec.h>
#include <libswresample/swresample.h>
};


//ffmpeg
class AudioDecodec {
public:
    //opensl es
    // Audio Object
    SLObjectItf slObjectItf = NULL;
    //引擎
    SLEngineItf slEngineItf = NULL;

    //混音器
    SLObjectItf outputMixObject = NULL;
    SLEnvironmentalReverbItf slEnvironmentalReverbItf = NULL;//环境混响
    //辅助效果对输出混合的影响，由缓冲区队列播放器使用
    SLEnvironmentalReverbSettings reverbSettings = SL_I3DL2_ENVIRONMENT_PRESET_STONECORRIDOR;


    //音频播放器
    SLObjectItf audioPlayerObject = NULL;
    SLAndroidSimpleBufferQueueItf simpleBufferQueueItf = NULL;
    SLPlayItf audioPlayItf;
    //声音
    SLVolumeItf slVolumeItf = NULL;
    //声道切换
    SLMuteSoloItf slMuteSoloItf = NULL;


    //音频
    int audioStreamsIndex = -1;
    AVCodecParameters *audioCodecParameters = NULL;
    AVCodecContext *audioCodecContex = NULL;
    CallBackToJava *callBackToJava = NULL;
    PlayStatus *playStatus = NULL;

    AVRational audioBaseTime;

    int sample_rate = 0;

    /**
      * 播放器线程
      */
    pthread_t threadPlay;

    //音频数据队列
    DataQueue *audioDataQueue = NULL;


    AVPacket *avPacket = NULL;
    AVFrame *avFrame = NULL;

    //重采样
    int nb;
    uint8_t *buffer = NULL;   //无符号8位类型
    int data_size = 0;

    //时长
    int duration = 0;

    //同步使用
    double clock;//总的播放时长
    double now_time;
    //回调时间判断
    double last_time = 0;

    //音量大小
    int volumePercent = 50;
    //初始化声道为立体声
    int mute = 2;

    /**
     * 解码线程锁
     */
    pthread_mutex_t codecMutex;
public:
    AudioDecodec(PlayStatus *ps, CallBackToJava *callBackToJava, int sampleRate);

    ~AudioDecodec();

    void startPlay();

    void initOpenSl();

    int getCurrentSampleRateForOpensles(int sample_rate);

    void pause();

    void resume();

    void setVolume(int percent);

    void setMute(int mute);

    void release();

    int getPcmData();
};


#endif //FFMPEGVIDEOPLAYER_AUDIODECODEC_H
